package com.krt.facenettydemo.netty;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * @author 殷帅
 * @version 1.0
 * @Description: AES工具类
 * @date 2016年7月20日
 */
public class AesUtil {

    /**
     * @param args
     */
    /**
     * 将二进制转换成16进制
     *
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte[] buf) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        int temp = 2;
        if (hexStr.length() < 1) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / temp];
        for (int i = 0; i < hexStr.length() / temp; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    /**
     * 加密
     *
     * @param content
     * @param aes
     * @return
     */
    public static byte[] getAESEncrypt(byte[] content, byte[] aes) {
        if (content == null || content.length < 0 || aes == null || aes.length < 0) {
            System.out.println("密钥或内容为空...");
            return null;
        }
        try {
            //补齐16位
            byte[] contentTemp;
            int w = content.length % 16;
            if (w != 0) {
                contentTemp = new byte[content.length + 16 - w];
                for (int i = 0; i < content.length; i++) {
                    contentTemp[i] = content[i];
                }
                ;
            } else {
                contentTemp = content;
            }
            SecretKeySpec sks = new SecretKeySpec(aes, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
            cipher.init(Cipher.ENCRYPT_MODE, sks);
            byte[] jiamihou = cipher.doFinal(contentTemp);
            return jiamihou;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密
     *
     * @param content
     * @param aes
     * @return
     */
    public static byte[] getAESDecrypt(byte[] content, byte[] aes) {
        if (content == null || content.length == 0 || aes == null || aes.length < 0) {
            System.out.println("密钥或内容为空...");
            return null;
        }
        try {
            SecretKeySpec sks = new SecretKeySpec(aes, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
            cipher.init(Cipher.DECRYPT_MODE, sks);
            byte[] jiemihou = cipher.doFinal(content);
            //去除多余空字节(0)
            return jiemihou;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 加密
     *
     * @param content
     * @param aes
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String getAESEncrypt(String content, String aes) throws UnsupportedEncodingException {
        return parseByte2HexStr(getAESEncrypt(content.getBytes("UTF-8"), aes.getBytes()));

    }

    /**
     * 加密
     *
     * @param content
     * @param aes
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String getAESAndBase64Encrypt(String content, String aes) throws UnsupportedEncodingException {
//        content = Base64Util.encode(content.getBytes("UTF-8"), 0, content.getBytes("UTF-8").length);
//        return parseByte2HexStr(getAESEncrypt(content.getBytes("UTF-8"), aes.getBytes()));
        return "";
    }

    /**
     * 解密
     *
     * @param content
     * @param aes
     * @return
     * @throws IOException
     * @throws UnsupportedEncodingException
     */
    public static String getAESAndBase64Decrypt(String content, String aes) throws UnsupportedEncodingException, IOException {
//        content = new String(getAESDecrypt(parseHexStr2Byte(content), aes.getBytes()), "UTF-8").replaceAll("\0", "");
//        return new String(Base64Util.decode(content.toString()), "UTF-8");
        return "";
    }

    /**
     * 解密
     *
     * @param content
     * @param aes
     * @return
     * @throws IOException
     * @throws UnsupportedEncodingException
     */
    public static String getAESDecrypt(String content, String aes) throws UnsupportedEncodingException, IOException {
        return new String(getAESDecrypt(parseHexStr2Byte(content), aes.getBytes()), "UTF-8").replaceAll("\0", "");
    }

    public static void main(String[] args) {
        try {
            String out_request_no = AesUtil.getAESEncrypt("10023&石城宁都年卡用户群&10000098", "0zwch8ofefdcfnc7");
            System.out.println("signkey===" + out_request_no);
            String out_request_no2 = AesUtil.getAESEncrypt("360702198412100315", "bpeu56n9o9o3udn3");
            System.out.println("signkey===" + out_request_no2);

            try {
                String ss = AesUtil.getAESDecrypt("0DDEAA3751995CED71DA8FC3EDCF9B2BAB48BE5241B2980C3E59160AA57B4D89", "bpeu56n9o9o3udn3");
                System.out.println("ss===" + ss + "**********");

            } catch (IOException e) {
                e.printStackTrace();
            }

/*
            String tag="weChatPay002";
//            String tag="weChatPay015";//吉安
            String returnOrderNum="T100129238";
            String returnServiceId="re"+returnOrderNum;
            String reamount="0.01";
            String totalPrice="0.01";
            String signkey= RandomUtil.getRandomStr(30);//签名：随机字符串长度30位
            String prestr = signkey.substring(0,16);//前16位

            String out_trade_no= AesUtil.getAESEncrypt(returnOrderNum,prestr);
            String out_request_no= AesUtil.getAESEncrypt(returnServiceId,prestr);
            String refund_amount=AesUtil.getAESEncrypt(reamount,prestr);
            String total_fee=AesUtil.getAESEncrypt(totalPrice,prestr);

            System.out.println("signkey==="+signkey);
            System.out.println("prestr==="+prestr);
            System.out.println("out_trade_no==="+out_trade_no);
            System.out.println("out_request_no==="+out_request_no);
            System.out.println("refund_amount==="+refund_amount);
            System.out.println("total_fee==="+total_fee);

            //微信
            String payurl = "http://www.krtpay.com:8888/krt-pay/api/wechat/refund";
            String content = "tag="+tag+"&out_trade_no="+ out_trade_no+"&signkey="+signkey+"&refund_fee="+refund_amount+"&total_fee="+total_fee+"&out_refund_no="+out_request_no;
            System.out.println("微信退款信息===="+content);
            String restr = HttpUtil.doPost(payurl,null,content);//请求接口
            System.out.println("restr===="+restr);
            JSONObject jsonObject = JSON.parseObject(restr);
            //支付完成申请，查询支付状态
            String result=jsonObject.getString("result");//00退款成功，修改状态
            System.out.println("微信退款信息===="+jsonObject);
*/

            //支付宝
//            tag="alipay002";//赣州旅游
            /*tag="alipay009";//吉安旅游
            String payurl = "http://www.krtpay.com:8888/krt-pay/api/alipay/refund";
            String content = "tag="+tag+"&out_trade_no="+ out_trade_no+"&signkey="+signkey+"&refund_amount="+refund_amount+"&out_request_no="+out_request_no;
            System.out.println("支付宝退款信息===="+content);
            String restr = HttpUtil.doPost(payurl,null,content);//请求接口
            System.out.println("restr===="+restr);
            JSONObject jsonObject = JSON.parseObject(restr);
            //支付完成申请，查询支付状态
            String result=jsonObject.getString("result");//00退款成功，修改状态
            System.out.println(result+"支付宝退款信息===="+jsonObject);
*/
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}